package com.wei.test.Util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

//class A {
//    public String getV1() {
//        return v1;
//    }
//
//    public void setV1(String v1) {
//        this.v1 = v1;
//    }
//
//    private String v1;
//
//    public long getV2() {
//        return v2;
//    }
//
//    public void setV2(long v2) {
//        this.v2 = v2;
//    }
//
//    private long v2;
//}
@Component
public class JsonUtil {

    public String obj2Str(Object obj) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(obj);
    }

    public <T> T str2Obj(String obj, Class<T> objType) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.readValue(obj, objType);
    }

    public Map bean2Map(Object bean) {
        return convertValue(bean, Map.class);
    }

    public <T> T convertValue(Object obj, Class<T> cls) {
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new JavaTimeModule());
        mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        T c = mapper.convertValue(obj, cls);
        return c;
    }

//    public static void main(String[] args) {
//        Map map = new HashMap();
//        map.put("v1", "v1");
//        map.put("v2", 2);
//        map.put("v3", 3);
//
//        A a;
//        a = convertValue(map, A.class);
//        logger.info(a.toString());
//    }

}